package com.xltt.vehicleControl.base;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.xltt.vehicleControl.BuildConfig;
import com.xltt.vehicleControl.R;
import com.xltt.vehicleControl.activity.LauncherActivity;
import com.xltt.vehicleControl.activity.LoginActivity;
import com.xltt.vehicleControl.activity.PowerSettingsActivity;
import com.xltt.vehicleControl.contants.Constants;
import com.xltt.vehicleControl.contants.ResponseCode;
import com.xltt.vehicleControl.util.ActivityManager;
import com.xltt.vehicleControl.util.Logger;
import com.xltt.vehicleControl.util.NetWorkUtils;
import com.xltt.vehicleControl.util.SharedPreferencesUtils;
import com.xltt.vehicleControl.util.ToastUtil;
import com.xltt.vehicleControl.view.HttpResponseDialog;
import android.util.SparseArray;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;

import butterknife.ButterKnife;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

/**
 * Description : BaseActivity 基类活动
 *
 * @author zhanghui
 * @date 2020/2/2
 */


public abstract class BaseActivity extends SwipeBackActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        initPresenter();
        ButterKnife.bind(this);
        initViews();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    /**
     * 抽象方法：实例化Presenter
     */
    protected abstract void initPresenter();

    /**
     * 抽象方法：初始化控件，一般在BaseActivity中通过ButterKnife来绑定，所以该方法内部一般我们初始化界面相关的操作
     *
     * @return 控件
     */
    protected abstract void initViews();


    /**
     * 抽象方法：得到布局id
     *
     * @return 布局id
     */
    protected abstract int getLayoutId();


    /**
     * 启动Fragment
     *
     * @param id       id
     * @param fragment 碎片
     */
    protected void startFragment(int id, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(id, fragment);
        fragmentTransaction.commit();
    }


    /**
     * 去登录
     */
    public void doLogin(int type){
        if(type == LoginActivity.LOGOUT_CODE){
            //清空密码信息
            if(Constants.DEBUG){
                SharedPreferencesUtils.setParam(this,LoginActivity.REQUETS_PASSWORD,"");
            }else{
                Settings.Global.putString(this.getContentResolver(), LoginActivity.REQUETS_PASSWORD,"");
            }
        }
        //跳转到登录界面
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,Constants.FIRST_BOOT,0);
        }else{
            Settings.Global.putInt(this.getContentResolver(), Constants.FIRST_BOOT,0);//记录退出了，处于第一次登录状态
        }
        startActivity(new Intent(this,LoginActivity.class));
        ActivityManager.getInstance().finishAllActivities(LoginActivity.class);
    }

    /**
     * 发送指令dialog提示结果
     */
    public void showDialog(int icon,String message){
        HttpResponseDialog mHttpResponseDialog = new HttpResponseDialog.Builder(this)
                .setIcon(icon)
                .setMessage(message)
                .create();
        if(!mHttpResponseDialog.isShowing()){
            mHttpResponseDialog.show();
        }
    }

    /**
     * 登录token过期
     * @param resultCode
     * @return
     */
    public boolean tokenInvalidation(int resultCode){
        Logger.d("resultCode = " + resultCode);
        if(resultCode == ResponseCode.CODE_1401 ||
                resultCode == ResponseCode.CODE_1402 ||
                resultCode == ResponseCode.CODE_1403 ||
                resultCode == ResponseCode.CODE_1404 ||
                resultCode == ResponseCode.CODE_1405 ||
                resultCode == ResponseCode.CODE_1406 ||
                resultCode == ResponseCode.CODE_1407 ||
                resultCode == ResponseCode.CODE_1408){
            return true;
        }
        return false;
    }

    /**
     * 第一次登录或者登录失效
     */
    public String LoginInvalidation(){
        String token = SharedPreferencesUtils.getParam(this,LoginActivity.TOKEN,"").toString();
        String userId = SharedPreferencesUtils.getParam(this,LoginActivity.USERID,"").toString();
        Logger.d("initViews() token = " + token + " , userId = " + userId);
        if(TextUtils.isEmpty(token) || TextUtils.isEmpty(userId)){
            //doLogin();
            return "";
        }
        return userId;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerNetworkReceiver();
        if(Constants.DEBUG){
        }else{
            //每次页面可见判断智能省电模式开关
            boolean state = Settings.Global.getInt(BaseActivity.this.getContentResolver(),"SETTINGS_AUTO_SAVE_POWER",1) == 1;
            Logger.d("Intelligent power mode , switch state = " + state);
            if(state){
                Settings.Global.putString(BaseActivity.this.getContentResolver(),"STATE_OPEN_4G","1" + System.currentTimeMillis());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unRegisterNetworkReceiver();
    }

    public void registerNetworkReceiver(){
        //注册网络监听广播
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkRevice,mIntentFilter);
        Logger.d("register network receiver");
    }
    public void unRegisterNetworkReceiver(){
        unregisterReceiver(mNetworkRevice);
        Logger.d("unregister network receiver");
    }

    private BroadcastReceiver mNetworkRevice = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean mAvailable = NetWorkUtils.isAvailable(BaseActivity.this);
            Logger.d("current network state = " + mAvailable);
            if(mAvailable){
            }else {
                ToastUtil.show(BaseActivity.this,BaseActivity.this.getString(R.string.please_connect_network_tip));
            }
        }
    };
    /**
     * 获取登录用户名格式
     * @return
     */
    public String getLoginUserFormat(){
        String userFormat = "";
        if(Constants.DEBUG){
            userFormat = SharedPreferencesUtils.getParam(this,LoginActivity.REQUETS_USERNAME_FORMAT,"60").toString();
        }else {
            userFormat = Settings.Global.getString(this.getContentResolver(), LoginActivity.REQUETS_USERNAME_FORMAT);
        }
        return TextUtils.isEmpty(userFormat) ? "60" : userFormat;
    }

    /**
     * 获取登录用户名
     * @return
     */
    public String getLoginUser(int type){
        String user = "";
        if(type == LoginActivity.BLE_LOGIN){
            if(Constants.DEBUG){
                user = SharedPreferencesUtils.getParam(this,LoginActivity.BLE_REQUETS_USERNAME,"").toString();
            }else {
                user = Settings.Global.getString(this.getContentResolver(), LoginActivity.BLE_REQUETS_USERNAME);
            }
        }else{
            if(Constants.DEBUG){
                user = SharedPreferencesUtils.getParam(this,LoginActivity.REQUETS_USERNAME,"").toString();
            }else {
                user = Settings.Global.getString(this.getContentResolver(), LoginActivity.REQUETS_USERNAME);
            }
        }

        return user;
    }

    /**
     * 获取登录密码
     * @return
     */
    public String getLoginPassword(int type){
        String password = "";
        if(type == LoginActivity.BLE_LOGIN){
            if(Constants.DEBUG){
                password = SharedPreferencesUtils.getParam(this,LoginActivity.BLE_REQUETS_PASSWORD,"").toString();
            }else {
                password = Settings.Global.getString(this.getContentResolver(), LoginActivity.BLE_REQUETS_PASSWORD);
            }
        }else{
            if(Constants.DEBUG){
                password = SharedPreferencesUtils.getParam(this,LoginActivity.REQUETS_PASSWORD,"").toString();
            }else {
                password = Settings.Global.getString(this.getContentResolver(), LoginActivity.REQUETS_PASSWORD);
            }
        }
        return password;
    }
    /**
     * 保存登录用户名格式
     * @return
     */
    public void setLoginUserFormat(String format){
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,LoginActivity.REQUETS_USERNAME_FORMAT,format);
        }else {
            Settings.Global.putString(this.getContentResolver(), LoginActivity.REQUETS_USERNAME_FORMAT,format);
        }
    }

    /**
     * 清空蓝牙传输过来的密码
     */
    public void cleanBluethUserInfo(){
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,LoginActivity.BLE_REQUETS_USERNAME,"");
            SharedPreferencesUtils.setParam(this,LoginActivity.BLE_REQUETS_PASSWORD,"");
        }else {
            Settings.Global.putString(this.getContentResolver(), LoginActivity.BLE_REQUETS_USERNAME,"");
            Settings.Global.putString(this.getContentResolver(), LoginActivity.BLE_REQUETS_PASSWORD,"");
        }
    }

    /**
     * 保存登录用户名
     * @return
     */
    public void setLoginUser(String user){
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,LoginActivity.REQUETS_USERNAME,user);
        }else {
            Settings.Global.putString(this.getContentResolver(), LoginActivity.REQUETS_USERNAME,user);
        }
    }
    /**
     * 保存登录密码
     * @return
     */
    public void setLoginPassword(String password){
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,LoginActivity.REQUETS_PASSWORD,password);
        }else {
            Settings.Global.putString(this.getContentResolver(), LoginActivity.REQUETS_PASSWORD,password);
        }
    }


    /*---------------------------------------------------------------------------以下是android6.0动态授权的封装十分好用---------------------------------------------------------------------------*/
    private int mPermissionIdx = 0x10;
    private SparseArray<GrantedResult> mPermissions   = new SparseArray<>();
    @SuppressLint("Override")
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        GrantedResult runnable = mPermissions.get(requestCode);
        if (runnable == null) {
            return;
        }
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            runnable.mGranted = true;
        }
        runOnUiThread(runnable);
    }
    public void requestPermission(String[] permissions, String reason, GrantedResult runnable) {
        if(runnable == null){
            return;
        }
        runnable.mGranted = false;
        Logger.d("MyApplication Build.VERSION.SDK_INT = " + Build.VERSION.SDK_INT + ",permissions.length = " + permissions.length);
        if (Build.VERSION.SDK_INT < 23 || permissions == null || permissions.length == 0) {
            runnable.mGranted = true;
            runOnUiThread(runnable);
            return;
        }
        final int requestCode = mPermissionIdx++;
        mPermissions.put(requestCode, runnable);

		/*
			是否需要请求权限
		 */
        boolean granted = true;
        for (String permission : permissions) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                granted = granted && checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                Logger.d("MyApplication granted = " + granted);
            }
        }
        Logger.d("MyApplication 222granted = " + granted);

        if (granted) {
            runnable.mGranted = true;
            runOnUiThread(runnable);
            return;
        }

		/*
			是否需要请求弹出窗
		 */
        boolean request = true;
        for (String permission : permissions) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                request = request && !shouldShowRequestPermissionRationale(permission);
            }
        }

        if (!request) {
            final String[] permissionTemp = permissions;
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setMessage(reason)
                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                requestPermissions(permissionTemp, requestCode);
                            }
                        }
                    })
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            GrantedResult runnable = mPermissions.get(requestCode);
                            if (runnable == null) {
                                return;
                            }
                            runnable.mGranted = false;
                            runOnUiThread(runnable);
                        }
                    }).create();
            dialog.show();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(permissions, requestCode);
            }
        }
    }

    public static abstract class GrantedResult implements Runnable{
        private boolean mGranted;
        public abstract void onResult(boolean granted);
        @Override
        public void run(){
            onResult(mGranted);
        }
    }


}
